package com.yanghx.springtxjta.service;

import com.yanghx.springtxjta.dao.CustomerRepository;
import com.yanghx.springtxjta.domain.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

/**
 * 代码方式事务 客户管理
 *
 * @author yangHX
 * createTime  2019/8/7 22:32
 */
@Service
@Slf4j
public class CustomerServiceTxInCode {
    @Resource
    private CustomerRepository customerRepository;
    @Resource
    private PlatformTransactionManager transactionManager;

    public Customer create(Customer customer) {
        log.info("CustomerServiceTxInCode  create customer : {}", customer.getUserName());
        if (null != customer.getId()) {
            throw new RuntimeException("用户已经存在");
        }
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();

        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        def.setTimeout(15);
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            customer.setUserName("code:" + customer.getUserName());
            customerRepository.save(customer);
//            error();
            transactionManager.commit(status);
            return customer;
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw e;
        }

    }

    private void error() {
        throw new RuntimeException("主动异常");
    }

}
